import { Toast } from "vant";
import Vue from 'vue';
import router from '../../router';
import { type } from "os";
/**
 * WebSocket 通讯服务
 */
var WebSocketServer = {
    host: "47.100.138.172",
    port: "9527",
    webSocket: null,    //WebSocket 对象
    panelTimer: null,
    /**
     * 连接通讯服务器
     * @param {*} param 
     */
    onStart: function (param = null) {
        var url = null;
        if (param != null) {
            var paramName = Object.keys(param)[0], paramValue = param[paramName];
            url = "ws://" + this.host + ":" + this.port + "?" + paramName + "=" + paramValue;
        } else {
            var user = localStorage.getItem("Now_User");
            
            user = JSON.parse(user);
            url = "ws://" + this.host + ":" + this.port + "?user_id=" + user.user_id;
        }
        this.webSocket = new WebSocket(url);
        //预加载服务器推送消息回调基类
        this.onMessage();

    },
    /**
     * 连接成功回回调函数
     */
    onOpen: function (func) {
        this.webSocket.open = func;
    },
    /**
     * 接收服务器推送消息回调函数
     * @param {*} func 
     */
    onMessage: function (func) {
        //this.webSocket.onmessage = func;
        if(!func || typeof func != "function"){
            func = function(){};
        }
        var baseOnMessage = this.baseOnMessage; //获取基类
        this.webSocket.onmessage = this.compose(baseOnMessage, func);   //设置监听
    },
    /**
     * 接受服务器推送消息回调基类函数
     * @param {*} response 
     */
    baseOnMessage: function (response) {
        var res = JSON.parse(response.data);
        console.log(res);
        if (res.method == "response") return false;
        var action = res.action,
            model = router.history.current.name,
            param = router.history.current.query;
        switch (action) {
            case 'UserChat':
                // console.log(router.history.current);
                if (model == 'Chat' && param.friend_id == res.target) {
                    return false;
                } else {
                    WebSocketServer.showPush({
                        user_header: res.header,
                        title: res.data.push.friend_alias,
                        content: res.data.push.chat_content,
                        href: 'Chat?friend_id=' + res.target,
                        time: res.data.push.push_time
                    });
                }
                break;
            case 'FriendPush':


                WebSocketServer.showPush({
                    user_header: res.header,
                    title: "好友请求：" + res.data.user_name,
                    content: res.data.content,
                    href: 'FriendPush',
                    time: '刚刚'
                });
                break;
            case 'Task':
                WebSocketServer.showPush({
                    user_header: res.header,
                    title: "您接收到一个任务",
                    content: res.data.content,
                    href: 'TaskList',
                    time: '刚刚'
                });
                break;
        }
    },
    /**
     * 发送信息
     * @param {*} data 
     */
    onSend: function (data) {
        if (typeof data == "object") data = JSON.stringify(data);
        this.webSocket.send(data);
    },
    compose: function (oneFunc, twoFunc) {
        return function (response) {
            return oneFunc(response, twoFunc(response));
        };
    },
    toHref: function (action) {
        location.href = 'index.html#/' + action;
    },
    getQueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.hash.split('?')[1].match(reg);
        if (r != null) return unescape(r[2]); return null;
    },
    /**
     * 向通讯服务器推送信息
     * @param {*} data 
     */
    sendPush: function (data) {
        if (data.target == null) {
            Toast("参数不完整：not defind target");
            return false;
        }
        if (data.action == null) {
            Toast("参数不完整：not defind action");
            return false;
        }
        //获取当前登录用户
        var user = localStorage.getItem("Now_User");
        user = JSON.parse(user);
        var method = 1; //通讯服务器执行方法
        if (data.method != null) method = data.method;
        var pushData = {
            method: method,         //通讯服务器执行方法
            target: data.target,    //发送对象
            user_id: user.user_id,  //当前发送的用户编号
            action: data.action,    //客户端操作方法
            header: data.header,
            data: data.data         //data数据包
        }
        //转成字符串
        pushData = JSON.stringify(pushData);
        //开始发送
        this.webSocket.send(pushData);
    },
    /**
     * 实例化推送框
     * @param {*} data 推送框基本参数
     * @param {*} data.user_header 用户头像
     * @param {*} data.title 推送框标题
     * @param {*} data.content 推送框内容
     * @param {*} data.time 推送框推送时间
     * @param {*} data.href 推送框点击跳转地址
     * @param {可选} data.elemId 推送框ID
     * @param {可选} data.showTime 推送框存在时间
     */
    showPush: function (data) {
        var elemId = "Contact_Push_Panel", showTime = 2000;
        //验证基本必备参数
        if (data.user_header == null) {
            Toast("参数不完整：not defind user header");
            return false;
        }
        if (data.title == null) {
            Toast("参数不完整：not defind title");
            return false;
        }
        if (data.content == null) {
            Toast("参数不完整：not defind content");
            return false;
        }
        if (data.href == null) {
            Toast("参数不完整：not defind href");
            return false;
        }
        if (data.time == null) {
            Toast("参数不完整：not defind time");
            return false;
        }
        if (data.showTime != null) showTime = data.showTime;
        if (data.elemId != null) elemId = data.elemId;
        //判断是否已存在推送框，存在则删除
        // var checkPanel = document.getElementById(elemId);
        // if (checkPanel) {
        //     clearInterval(WebSocketServer.panelTimer);
        //     document.querySelector("#app").removeChild(checkPanel);
        // }
        //拼接推送框节点
        var pushPanelElem = '<div action="' + data.href + '"  id="' + elemId + '" class="ts_Contact_Push_Panel">'
            + '<a>'
            + '<img src="' + data.user_header + '">'
            + '<div class="ts_Contact_Push_Panel-main">'
            + '<span class="ts_Contact_Push_Panel-title">' + data.title + '</span>'
            + '<span class="ts_Contact_Push_Panel-content">' + data.content + '</span>'
            + '</div>'
            + '<div class="ts_Contact_Push_Panel-time">'
            + '<span>' + data.time + '</span>'
            + '</div>'
            + '</a>'
            + '</div>';
        //写入节点
        document.querySelector("#" + elemId + " a").setAttribute('href', '/#/' + data.href);
        document.querySelector("#" + elemId + " img").setAttribute('src', data.user_header);
        document.querySelector("#" + elemId + " .ts_Contact_Push_Panel-title").innerText = data.title;
        document.querySelector("#" + elemId + " .ts_Contact_Push_Panel-content").innerText = data.content;
        document.querySelector("#" + elemId + " .ts_Contact_Push_Panel-time span").innerText = data.time;
        document.getElementById(elemId).setAttribute('class', 'ts_Contact_Push_Panel show');
        // document.querySelector("#app").innerHTML += pushPanelElem;
        // document.getElementById(elemId).addEventListener('click',function(){
        //     var action = document.getElementById(elemId).getAttribute("action");
        //     WebSocketServer.toHref(action);
        // });
        // 定时器删除推送框
        WebSocketServer.panelTimer = setInterval(function () {
            // var panel = document.getElementById(elemId);
            // document.querySelector("#app").removeChild(panel);
            document.getElementById(elemId).setAttribute('class', 'ts_Contact_Push_Panel');
            clearInterval(WebSocketServer.panelTimer);
        }, showTime);
    },
    userChat: function (data) {

    },
    addFriend: function (data) {

    }
}

export {
    WebSocketServer
}
/**
 *
 * <div id="Contact_Push_Panel" class="ts_Contact_Push_Panel">
      <a href="/#/Chat?friend_id=10008">
      <img src="http://contact.yhong.info/uploads/img/20191020/d71c86720d2bd9c85bc966ad0b7db8b5.jpg">
      <div class="ts_Contact_Push_Panel-main">
        <span class="ts_Contact_Push_Panel-title">我不配呀</span>
        <span class="ts_Contact_Push_Panel-content">遍体鳞伤我不配</span>
      </div>
      <div class="ts_Contact_Push_Panel-time">
        <span>14:57</span>
      </div>
      </a>
    </div>
 */